<template>
  <section class="todoapp">
    <!-- 头部部分 -->
    <todo-header @addTask="hAddTask"></todo-header>
    <!-- 主体部分 -->
    <todo-main
      :list="showList"
      @del="delTask"
      @changeDone="hChangeDone"
      @isAll='hisAll'
    ></todo-main>

    <!-- 底部部分 -->
    <todo-footer
      :list="list"
      @clearDone="hclearDone"
      @changeType="hchangeType"
    ></todo-footer>
  </section>
</template>

<script>
import TodoHeader from "./components/TodoHeader.vue";
import TodoMain from "./components/TodoMain.vue";
import TodoFooter from "./components/TodoFooter.vue";

export default {
  components: { TodoHeader, TodoMain, TodoFooter },
  data() {
    return {
      // list: [
      //   { id: 1, name: "吃饭", isDone: true },
      //   { id: 2, name: "睡觉", isDone: false },
      //   { id: 3, name: "打豆豆", isDone: true },
      // ],
      list:  JSON.parse(localStorage.getItem('list')) || [],
      type: "all",
    };
  },
  methods: {
    delTask(id) {
      const index = this.list.findIndex((item) => item.id === id);
      this.list.splice(index, 1);
    },
    hChangeDone(id) {
      const obj = this.list.find((item) => item.id === id);
      obj.isDone = !obj.isDone;
    },
    hAddTask(name) {
      this.list.push({
        id: this.list.length ? this.list[this.list.length - 1].id + 1 : 1,
        name,
        isDone: false,
      });
    },
    hclearDone() {
      this.list = this.list.filter((item) => !item.isDone);
    },
    hchangeType(type) {
      this.type = type;
    },
    hisAll(val){
      this.list.forEach(item=>item.isDone = val)
    }
  },
  computed: {
    showList() {
      if (this.type === "all") {
        return this.list;
      } else if (this.type === "active") {
        return this.list.filter((item) => !item.isDone);
      } else {
        return this.list.filter((item) => item.isDone);
      }
    },
  },
  watch:{
    list:{
      deep:true,
      handler(){
        localStorage.setItem('list',JSON.stringify(this.list))
      }
    }
  }
};
</script>

<style></style>
